<template>
  <div id="image-upload">
    <a-upload
      v-model:file-list="fileList"
      name="avatar"
      list-type="picture-card"
      :show-upload-list="false"
      :before-upload="beforeUpload"
      :custom-request="handleUpload"
    >
      <img class="image" v-if="picture?.url" :src="picture?.url" alt="avatar" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">点击上传图片</div>
      </div>
    </a-upload>
  </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
import type { UploadProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { savePictureUsingPost } from '@/api/pictureController.ts'

const fileList = ref([])
const loading = ref<boolean>(false)

interface Props {
  picture?: API.Picture
  onSuccess?: (pictureVO: API.PictureVO) => void
  spaceId?: number
}

const props = defineProps<Props>()

const handleUpload = async ({ file }: any) => {
  loading.value = true
  try {
    const params = props.picture ? { id: props.picture.id } : {}
    const res = await savePictureUsingPost(
      {
        ...params,
        spaceId: props.spaceId,
      },
      {},
      file,
    )
    if (res.data.code != 0) {
      return
    }
    props.onSuccess?.(res.data.data)
  } catch (error) {
    console.log(error.message)
  }
  loading.value = false
}

const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传格式为jpeg，和png')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不超过2MB')
  }
  return isJpgOrPng && isLt2M
}
</script>
<style scoped lang="scss">
#image-upload {
  width: 100%;
  height: 100%;

  :deep(.ant-upload) {
    width: 100% !important;
    height: 300px !important;
  }

  .image {
    height: 300px;
    object-fit: cover;
  }
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 16px;
  color: #666;
}
</style>
